
// 创建 websocket.js文件
export default class WebsocketTask{
  constructor(url,time){
     this.url = url;
     this.data = null;
     this.isOpenSocket = false;
     // 心跳检测
     this.timeout = time;
     this.heartbeat = null;
 
     try{
       return this.connectSocketInit();
     }catch(e){
       this.isOpenSocket = false;
       this.reconnect();
     } 
  }

  connectSocketInit(){
    this.socketTask = uni.connectSocket({
      url: this.url,
      header: {
      	'content-type': 'application/json'
      },
      success: (res) => {
      	console.log(res);
      },
      fail: (rej) => {
      	console.error(rej);
      }
    });

    this.socketTask.onOpen((res)=>{
      clearInterval(this.heartbeat);
      this.isOpenSocket = true;
      this.start();
      this.socketTask.onMessage((res)=>{
         let data = JSON.parse(res.data);
         
         console.log('收到服务器内容：',data);
      })
    })

    this.socketTask.onClose(()=>{
		// uni.showToast({
		// 	title: 'reconnect'
		// });
      this.isOpenSocket = false;
	  getApp().globalData.socketObj=null;
      this.reconnect();
    })
  }

  //发送消息
  send(data){
    this.socketTask.send({
       data
    })
  }
  //开启心跳检测
  start(){
    this.heartbeat = setInterval(()=>{
       this.data = {value:'1'}
       this.send(JSON.stringify(this.data));
    }, this.timeout);
  }
  // 重新连接
  reconnect(){
   clearInterval(this.heartbeat);
   if(!this.isOpenSocket){
     setTimeout(()=>{
        this.connectSocketInit();
     }, 3000)
   }
  }
}